package com.hs.core.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.CleanupFailureDataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.orm.hibernate3.support.OpenSessionInViewFilter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class HsOpenSessionInViewFilter extends OpenSessionInViewFilter{
	protected void doFilterInternal(HttpServletRequest request,      
	        HttpServletResponse response,     
	        FilterChain filterChain) throws ServletException, IOException {     
	        SessionFactory sessionFactory = lookupSessionFactory();     
	        logger.debug("Opening Hibernate Session in OpenSessionInViewFilter");     
	        Session session = getSession(sessionFactory);     
	        TransactionSynchronizationManager.bindResource(     
	                sessionFactory, new SessionHolder(session));     
	        try {  
	            filterChain.doFilter(request, response);     
	            }     
	        finally {     
	            TransactionSynchronizationManager.unbindResource(sessionFactory);     
	        logger.debug("Closing Hibernate Session in OpenSessionInViewFilter");     
	        closeSession(session, sessionFactory);     
	        }     
	}      
	protected Session getSession(SessionFactory sessionFactory)     
	                   throws DataAccessResourceFailureException {     
	        Session session = SessionFactoryUtils.getSession(sessionFactory, true);     
	        session.setFlushMode(FlushMode.AUTO);     
	        return session;     
	}     
	protected void closeSession(Session session,      
	        SessionFactory sessionFactory)throws CleanupFailureDataAccessException {
		session.flush();
		super.closeSession(session, sessionFactory);
	  //  SessionFactoryUtils.closeSession(session);     
	} 

}
